<?php
/**
 * Created by PhpStorm.
 * User: sofwu
 * Date: 2019/1/11
 * Time: 下午3:13
 */
namespace App\Http\Controllers\Api\V1;


use App\Model\Order;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{

    public function __construct()
    {
        $this->middleware('api.auth', ['only' => ['pay']]);
    }

    /**
     * 支付
     */
    public function pay(){
        $rules = [
            'order_sn' => ['required'],
        ];

        $payload = app('request')->only('order_sn');

        $validator = app('validator')->make($payload, $rules);

        if ($validator->fails()) {
            throw new \Dingo\Api\Exception\ResourceException('Could not post order store.', $validator->errors());
        }


        try{
            $order = Order::where(['order_sn'=>$payload['order_sn'], 'order_status'=>0, 'pay_status'=>0])->first();

            if (!$order) { // 如果订单不存在 或者 订单已经支付过了
                throw new \Dingo\Api\Exception\ResourceException('找不到订单');
            }

            // 将元转成分
            $total = floatval($order->total_amount);
            $total = round($total * 100);
            if (empty($total)) {
                $total = 100;
            }
            $result = app('EasyWeChat')->payment()->order->unify([
                'body' => '为'.$order->name.'祈福',
                'out_trade_no' => $order->order_sn,
                'total_fee' => $total,
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $order->user->oauthUser()->where('oauth', 'miniapp')->value('openid'),
            ]);

            if($result['result_code'] == 'SUCCESS'){
                $jssdk = app('EasyWeChat')->payment()->jssdk;
                $config = $jssdk->sdkConfig($result['prepay_id']); // 返回数组
            }



            return $this->response->array($config);

        }catch (\Exception $exception){
            Log::info($exception->getMessage());
            throw new \Dingo\Api\Exception\StoreResourceFailedException($exception->getMessage());
        }



    }


    /**
     * 支付回调通知
     */
    public function notify()
    {
        $response = app('EasyWeChat')->payment()->handlePaidNotify(function($message, $fail){
            $order = Order::where('order_sn', $message['out_trade_no'])->first();
            if (!$order || $order->pay_status || $order->pay_time) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->pay_time = time(); // 更新支付时间为当前时间
                    $order->pay_status = 1;
                    $order->order_status = 1;

                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = 2;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save(); // 保存订单

            return true; // 返回处理完成
        });

        return $response;
    }
}